package top.go2do.auth.business.role.controller;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.go2do.auth.business.role.module.*;
import top.go2do.auth.business.role.service.RoleService;
import top.go2do.common.annotation.UserInfoFill;
import top.go2do.common.controller.TomatoController;
import top.go2do.common.module.UserInfoBO;
import top.go2do.common.module.pageQuery.PageResult;

import java.util.List;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/6/13 11:53
 */
@Slf4j
@RequestMapping("/roles")
@RestController
public class RoleController implements TomatoController<RolePO, RoleCreateForm, RoleModifyForm, Long, RoleQueryCondition, RoleQueryAllCondition, RoleListVO> {

    @Autowired
    private RoleService roleService;

    @Override
    public RolePO create(RoleCreateForm createForm, UserInfoBO userInfo) {
        log.info("roles create appId:{}, roleName:{}", userInfo.getAppId(), createForm.getRoleName());
        createForm.setAppId(userInfo.getAppId());
        createForm.setUserId(userInfo.getUserId());
        return roleService.create(createForm);
    }

    @Override
    public void modifyById(Long id, RoleModifyForm modifyForm, UserInfoBO userInfo) {
        modifyForm.setRoleId(id);
        modifyForm.setUserId(userInfo.getUserId());
        roleService.modifyById(modifyForm);
    }

    @Override
    public void removeById(Long id, UserInfoBO userInfo) {
        roleService.removeById(id);
    }

    @Override
    public RolePO getById(Long id) {
        return roleService.getById(id);
    }

    @Override
    public List<RoleListVO> listAll(RoleQueryAllCondition condition) {
        List<RolePO> poList = roleService.listAll(condition);
        List<RoleListVO> volist = roleService.po2vo(poList);
        return volist;
    }

    @Override
    public PageResult<RoleListVO> pageQuery(RoleQueryCondition roleQueryCondition) {
        PageResult<RolePO> pageResult = roleService.pageQuery(roleQueryCondition);
        List<RoleListVO> volist = roleService.po2vo(pageResult.getList());
        PageResult<RoleListVO> finalResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, finalResult);
        finalResult.setList(volist);
        return finalResult;
    }

    @PatchMapping("/setPerms")
    public void setPermissions(@Valid @RequestBody RolePermissionsForm rolePermissionsForm, @UserInfoFill UserInfoBO userInfo) {
        rolePermissionsForm.setUserId(userInfo.getUserId());
        roleService.setPermissions(rolePermissionsForm);
    }
}
